var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var app = getApp();
var inviteuid = 0;
const Upyun = require('../../utils/upyun-wxapp-sdk');
const upyun = new Upyun({
  bucket: util.upyun_bucket,
  operator: util.upyun_opterator,
  getSignatureUrl: util.upyun_getSignUrl
})
Page({
  data: {
    util: util,
    tc: 0,

    
    isIphone_x: false,
    nav_bgColor: '#ffffff',
    
    token: '',
    uid: 0,
    userInfo:{},
    isShow: false,
    user_jifen: 0,
    tx:"",

    nameDisEdit:true,
    phoneDisEdit:true,
    addrDisEdit:true
  },
  onLoad: function(data){
    
    var that = this;
    var tc = app.get_tc();//简体繁体转换
    console.log("tc======",tc);
    that.setData({
      tc: tc,
    });
    inviteuid = data.inviteuid ? data.inviteuid : '';
    
   
    //获取颜色配置
    app.getColorSetData(function (color) {
      that.setData({
        colorSet: color,
      })
      that.resetNavColor();
    });


    wx.getSystemInfo({
      success: function(res) {
        var isIphone_x = (res.model.indexOf('iPhone X') >= 0);
        that.setData({
          isIphone_x: isIphone_x,
          screen_h: res.windowHeight,
        });
      }
    });
    var titleName = tc == 1 ? '會員' : '会员';

    wx.setNavigationBarTitle({
      title: titleName,
    })

    //获取关于等信息
    app.getAllAbout('contact', function (res) {
      that.setData({
        contact_phone: res
      })
    });

  },
  onShow:function(){
    this.getLoginInfo();
  },

  nameEditAction:function(){
    let disEdit = !(this.data.nameDisEdit);
    this.setData({
      nameDisEdit: disEdit
    })
  },
  phoneEditAction:function(){
    let disEdit = !(this.data.phoneDisEdit);
    this.setData({
      phoneDisEdit: disEdit
    })
  },
  addrEditAction:function(){
    let disEdit = !(this.data.addrDisEdit);
    this.setData({
      addrDisEdit: disEdit
    })
  },

  getLoginInfo: function(){
    var that = this;
    app.getLoginUserInfo(function (res) {
      console.log("mine login:", res);
      res.showaddress = '';
      that.setData({
        uid: res.uid,
        token: res.token,
        userInfo: res
      });
    });
  },

  goAtherPage: function(e){
    console.log("goAtherPage",e)
      var url = e.currentTarget.dataset.link;
      wx.navigateTo({ url: url })
  },
  goAtherPageRedirect: function(e){
      var url = e.currentTarget.dataset.link;
      wx.redirectTo({url: url})
  },



  //保存formId
  submitFormId: function (e) {
    app.saveFormId(e.detail.formId);
    var path = e.detail.value.nav_path;
    if (path && path.indexOf('navto:') == 0) {
      path = path.slice(6);
    }
    if (path) {
      wx.reLaunch({
        url: path,
      })
    }
  },



  //页面分享
  onShareAppMessage: function () {
    var invUid = this.data.uid ? this.data.uid : '';

    var path = '/pages/mine/mine?inviteuid=' + invUid;
    console.log("分享给好友：" + path);
     if (util.orgid == "21398") {
      return {
        title: this.data.tc == 1 ? '尚品高質凍肉海產零售批發小程序開通啦，歡迎下單購買！！！':'尚品高质冻肉海产零售批发小程序开通啦，欢迎下单购买！！！',
        path: path
      };
    } else{
      return {
        title: '',
        path: path
      };
    }
    
  },


  resetNavColor: function () {
    var bg_color = '#d8202d';
    var fg_color = '#ffffff';
    if (this.data.colorSet) {
      var colorJO = this.data.colorSet;
      bg_color = colorJO.titlebg;
      fg_color = colorJO.titlefont;
    }
    wx.setNavigationBarColor({
      frontColor: fg_color,
      backgroundColor: bg_color
    });
    this.setData({
      frontColor: fg_color,
      backgroundColor: bg_color
    })
  },

   uploadTX: function () {
    var that = this;
    wx.chooseImage({
      count: 1,

      sizeType: ['compressed'],
      sourceType: ['album'],
      success: function (res) {

        const imageSrc = res.tempFilePaths[0]
        let lastIndex_1 = imageSrc.lastIndexOf('/');
        let lastIndex_2 = imageSrc.lastIndexOf('.');
        if (lastIndex_2 - lastIndex_1 > 28) {
          lastIndex_1 = lastIndex_2 - 28;
        }
        var imgName = imageSrc.slice(lastIndex_1);
        var avatarUrl = '/avatar/xcx/' + imgName;
        console.log("定义路径：", res);
        upyun.upload({
          localPath: imageSrc,
          remotePath: avatarUrl,
          success: function (res) {
            console.log("上传图片结果：", res);
            var newUrl = util.upyun_imgHost + avatarUrl;
            console.log("链接地址：", newUrl);
            that.setData({
              tx: newUrl
            })
            that.saveCard();
          },
          fail: function ({errMsg}) {
            console.log('uploadImage fail, errMsg is', errMsg)
          }
        })
      },

      fail: function ({errMsg}) {
        console.log('chooseImage fail, err is', errMsg)
      }

      
    });
  },

  nameEdited:function(e){
    if(e.detail.value){
      let u_info = this.data.userInfo;
      u_info.uname = e.detail.value;
      this.setData({
        userInfo: u_info
      });
    }
  },
  phoneEdited: function (e) {
    if (e.detail.value) {
      let u_info = this.data.userInfo;
      u_info.phone = e.detail.value;
      this.setData({
        userInfo: u_info
      });
    }
  },
  addressEdited: function (e) {
    if (e.detail.value) {
      let u_info = this.data.userInfo;
      u_info.address = e.detail.value;
      this.setData({
        userInfo: u_info
      });
    }
  },

  saveCard: function(){
    wx.showLoading({
      title: '',
      mask:true
    })
    var that = this;
    var tmpmd5 = utilMd5.hexMD5(that.data.uid + "usercominfo" + that.data.token);
 
      var params = {
        "privatekey": tmpmd5,
        "ac": "usercominfo",
        "uid": that.data.userInfo.uid,
        "edituid": that.data.userInfo.uid,
        "realname": that.data.userInfo.uname,
        "phone": that.data.userInfo.phone,
        "address": that.data.userInfo.address,
        "avatar": that.data.tx,
   
      };
      console.log("编辑资料params：", params);
      util.api({
        data: params,
        method: "POST",
        success: function (responseData) {
          console.log(responseData);
          wx.hideLoading();
          if(responseData.data.res){
            app.dialogToast("編輯成功", "success", function(){
              // wx.reLaunch({ url: '/pages/ziliao/ziliao' });
            });
            that.saveAddress();
          } else {
            wx.showToast({
              title: responseData.data.msg,
            })
          }
        }
      });

  },

  saveAddress: function () {
    var that = this;
    var privatekey = utilMd5.hexMD5(that.data.uid + "addaddress" + that.data.token);
    util.api({
      data: {
        "privatekey": privatekey,
        "ac": "addaddress",
        "uid": that.data.userInfo.uid,
        "name": that.data.userInfo.uname,
        "phone": that.data.userInfo.phone,
        "address": that.data.userInfo.address,
        "psd_phone": '',
        "default": 1
      },
      method: "POST",
      success: function (responseData) {
        console.log("保存地址成功");
      }
    });
  },

})